package org.ttjhome.html.struts.company;

import java.io.File;
import java.util.List;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.DynaActionForm;
import org.apache.struts.actions.DispatchAction;
import org.json.JSONArray;
import org.json.JSONObject;
import org.ttjhome.db.dbo.Company;
import org.ttjhome.db.dbo.Job;
import org.ttjhome.db.dbo.User;
import org.ttjhome.html.struts.ActionMessageRegistry;
import org.ttjhome.html.struts.candidate.Constants;
import org.ttjhome.html.struts.common.SecurityConstants;
import org.ttjhome.server.HunterServiceFactory;
import org.ttjhome.util.StringUtils;

public class CompaniesAction extends DispatchAction{

	private static final Logger logger = Logger.getLogger(CompaniesAction.class
			.getName());
	
	
	public ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		return list(mapping, form, request, response);
	}

	public ActionForward list(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		logger.info("Entering execute of CompaniesAction with form"+form);
		ActionForward actionForward = mapping.findForward("success");
		
		DynaActionForm queryForm = (DynaActionForm) form;
		ActionMessages actionMessages = new ActionMessages();
		if (!actionMessages.isEmpty())
		{
			actionMessages.add("pageerror",  new ActionMessage( "ERR_PROBLEM_IN_INPUT" ));
			request.setAttribute("ACTION_MESSAGES", actionMessages);
			return mapping.findForward("success");
		}
		  
	
		List<Company> companies = HunterServiceFactory.createHunterService().getCompanies();
		request.setAttribute(Constants.ATTR_COMPANIES_LIST, companies);
		request.setAttribute(Constants.ATTR_COMPANIES_COUNT, companies.size());
	
		//init the query form field value for display
		initQueryForm(request, queryForm);
		
		return actionForward;
	}
	
	

	public ActionForward create(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
	{
	
		logger.info("Entering create of CompanyAction with form"+form);
		ActionForward actionForward = mapping.findForward("success");
		DynaActionForm createForm = (DynaActionForm) form;
		User user = SecurityConstants.gSessionAccount.get(request);
		ActionMessages actionMessages = new ActionMessages();
		String filter = (String) createForm.get(Constants.KEY_FILTER); 
		
		if (!StringUtils.isEmpty(filter))
		{
			if (!isTokenValid(request, true))
			{
				resetToken(request);
				return mapping.findForward(Constants.FORWARD_LIST);
			}
			verifyCompanyForm(actionMessages,createForm);
			if (!actionMessages.isEmpty())
			{
				actionMessages.add(Constants.PAGE_ERROR, ActionMessageRegistry.PAGE_ERROR);
				request.setAttribute(Constants.ACTION_MESSAGES, actionMessages);
				saveToken(request);
				return mapping.findForward(Constants.FORWARD_FAILURE);
			}
			
			Company company = new Company();
			copyFormValueTocompany(request,company, createForm,user);
			try
			{
				company = HunterServiceFactory.createHunterService().saveCompany(company);
			}catch(Exception e)
			{
				actionMessages.add(Constants.PAGE_ERROR, ActionMessageRegistry.PAGE_ERROR);
				request.setAttribute(Constants.ACTION_MESSAGES, actionMessages);
				saveToken(request);
				return mapping.findForward(Constants.FORWARD_FAILURE);
			}
			
			request.setAttribute(Constants.ATTR_SUCCESS_MESSAGE_TYPE, Constants.ATTR_SUCCESS_MESSAGE_TYPE_SAVING);
			request.setAttribute(Constants.ATTR_SUCCESS_COMPANY,company);
			actionForward = mapping.findForward(Constants.FORWARD_LIST); 
			createForm.set(Constants.KEY_FILTER, "");
		}else
		{	
			saveToken(request);
			createForm.set(Constants.KEY_FILTER, Constants.KEY_FILTER_CREATE);	
		}
		
		return actionForward;
	}
	 
	
	public ActionForward edit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
	{
	
		logger.info("Entering edit of CompanyAction with form"+form);
		ActionForward actionForward = mapping.findForward("success");
		DynaActionForm editForm = (DynaActionForm) form;
		User user = SecurityConstants.gSessionAccount.get(request);
		ActionMessages actionMessages = new ActionMessages();
		String filter = (String) editForm.get(Constants.KEY_FILTER); 
		String companyID=(String)editForm.get(Constants.INPUT_COMPANY_ID);
		
		if (StringUtils.isEmpty(companyID))
		{
			logger.info("The companyID is missing, redirect to company list page!");
			return mapping.findForward(Constants.FORWARD_LIST);
		}
		
		Company company = HunterServiceFactory.createHunterService().getCompany(Long.valueOf(companyID));
		
		if (!StringUtils.isEmpty(filter))
		{
			if (!isTokenValid(request, true))
			{
				resetToken(request);
				return mapping.findForward(Constants.FORWARD_LIST);
			}
			verifyCompanyForm(actionMessages,editForm);
			if (!actionMessages.isEmpty())
			{
				actionMessages.add(Constants.PAGE_ERROR, ActionMessageRegistry.PAGE_ERROR);
				request.setAttribute(Constants.ACTION_MESSAGES, actionMessages);
				saveToken(request);
				return mapping.findForward(Constants.FORWARD_FAILURE);
			}
			
			copyFormValueTocompany(request,company, editForm,user);
			try
			{
				company = HunterServiceFactory.createHunterService().saveCompany(company);
			}catch(Exception e)
			{
				actionMessages.add(Constants.PAGE_ERROR, ActionMessageRegistry.PAGE_ERROR);
				request.setAttribute(Constants.ACTION_MESSAGES, actionMessages);
				saveToken(request);
				return mapping.findForward(Constants.FORWARD_FAILURE);
			}
			logger.info("Updated Company "+company.getName() +" successfully ");
			request.setAttribute(Constants.ATTR_SUCCESS_MESSAGE_TYPE, Constants.ATTR_SUCCESS_MESSAGE_TYPE_SAVING);
			request.setAttribute(Constants.ATTR_SUCCESS_COMPANY,company);
			actionForward = mapping.findForward(Constants.FORWARD_LIST);
			editForm.set(Constants.KEY_FILTER, "");
		}else
		{	
			saveToken(request);
			editForm.set(Constants.KEY_FILTER, Constants.KEY_FILTER_EDIT);	
			copyCompanyToForm(company, editForm, request);
		}
		
		return actionForward;
	}
	 

	
	private void copyCompanyToForm(Company company,
			DynaActionForm editForm, HttpServletRequest request) {
		editForm.set(Constants.INPUT_COMPANY_NAME, company.getName());
		editForm.set(Constants.INPUT_COMPANY_ADDRESS, company.getAddress());
		editForm.set(Constants.INPUT_COMPANY_MAILBOX, company.getMailBox());
		editForm.set(Constants.INPUT_COMPANY_ID,String.valueOf(company.getId()));
		editForm.set(Constants.INPUT_COMPANY_POC,company.getPoc());
		editForm.set(Constants.INPUT_COMPANY_PHONENUMBER,company.getPhoneNumber());
		editForm.set(Constants.INPUT_COMPANY_DESCRIPTION,company.getDescription());
	
	}

	private void copyFormValueTocompany(HttpServletRequest request, Company company,
			DynaActionForm form, User user) {
		String companyName = form.getString(Constants.INPUT_COMPANY_NAME);
		String companyPOC = form.getString(Constants.INPUT_COMPANY_POC);
		String address = form.getString(Constants.INPUT_COMPANY_ADDRESS);
		String phoneNumber = form.getString(Constants.INPUT_COMPANY_PHONENUMBER);
		String description = form.getString(Constants.INPUT_COMPANY_DESCRIPTION);
		String email = form.getString(Constants.INPUT_COMPANY_MAILBOX);
		company.setName(companyName);
		company.setAddress(address);
		company.setDescription(description);
		company.setMailBox(email);
		company.setPhoneNumber(phoneNumber);
		company.setPoc(companyPOC);
		
		
		
	}
	
	
	public ActionForward getJobs(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String companyId = request.getParameter("companyId");
		logger.info("Entering getJobs of CompanyAction with id "+companyId);
		List<Job> jobs = HunterServiceFactory.createHunterService().getJobsByCompanyId(companyId);
		JSONObject json = new JSONObject();
		JSONArray array  = new JSONArray();
		
		for(Job job:jobs){
			JSONObject tmp = new JSONObject();
			tmp.put("filename",job.getFilename());
			tmp.put("url", job.getUrl());
			tmp.put("id", job.getId());
			tmp.put("name", job.getName());
			tmp.put("tags",job.getTagsAsString());
			tmp.put("description", job.getDescription());
			array.put(tmp);
		}
		json.put("result", 0);
		json.put("data", array);
		response.setContentType("application/json");
		response.getWriter().write(json.toString());
		return null;
	}
	
	
	
	public ActionForward createJob(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String companyId = request.getParameter("companyId");
		String jobName = request.getParameter("name");
		String description = request.getParameter("description");
		String url = request.getParameter("file");
		String filename = request.getParameter("filename");
		logger.info("Entering createJob of CompanyAction with id "+companyId +" jobname "+jobName
				+" description "+description+" url "+url+" filename "+filename);
		JSONObject json = new JSONObject();
		
		
		if(companyId==null||companyId.length()==0){

			json.put("result", -1);
			json.put("data", "");
		}else{
			Company company =HunterServiceFactory.createHunterService().getCompany(Long.valueOf(companyId));
			if(company==null){
				logger.info("Can not find company ");
				json.put("result", -1);
				json.put("data", "");
			}else{
				Job job = new Job();
				//rename jd file
				String 	contextPath =this.getServlet().getServletContext().getRealPath("");
				filename = StringUtils.removeWhiteSpace(filename);
				String realfilepath =contextPath+"/upload/Filedata/"+filename;
				logger.info("In createJob realfilepath "+realfilepath);
				try{
					String renameTo=contextPath+"/upload/"+company.getName();
					
					File file = new File(realfilepath);
					if(!file.exists()) throw new RuntimeException("File not exists");
					File renameToPath = new File(renameTo);
					if(!renameToPath.exists()) renameToPath.mkdirs();
					file.renameTo(new File(renameTo+"/"+filename));
					logger.info("move file "+filename+ " to "+renameTo+" successfully");
					job.setCompany(company);
					job.setName(jobName);
					job.setDescription(description);
					job.setUrl(request.getContextPath()+"/upload/"+company.getName()+"/"+filename);
					job.setFilename(filename);
					job = HunterServiceFactory.createHunterService().saveJob(job);
					json.put("result", 0);
					JSONObject tmp = new JSONObject();
					tmp.put("filename",job.getFilename());
					tmp.put("url", job.getUrl());
					tmp.put("id", job.getId());
					tmp.put("name", job.getName());
					tmp.put("tags", "");
					tmp.put("description", job.getDescription());
					
					json.put("data", tmp);
				}catch(Throwable t){
					logger.info("Fatal error in rename uploaded file "+t);
				}
			}
		}
			
		response.setContentType("application/json");
		response.getWriter().write(json.toString());
		return null;
	}
	

	private void verifyCompanyForm(ActionMessages actionMessages,
			DynaActionForm createForm) {
		String companyName = createForm.getString(Constants.INPUT_COMPANY_NAME);
		if(StringUtils.isEmpty(companyName))
		{
			actionMessages.add(Constants.INPUT_ERRORS, ActionMessageRegistry.COMPANY_NAME_INVALID);
			actionMessages.add(Constants.INPUT_COMPANY_NAME, ActionMessageRegistry.COMPANY_NAME_INVALID);
		}
		
		
		
	}


	public static void initQueryForm(HttpServletRequest request, DynaActionForm queryForm) {
		
	}
}
